from text_util import *
from sys_util import read_config_value
from file_util import *
from English_util import *
import os
import datetime
import json

config_file = 'config.ini'
json_file = 'E_prompt.json'
log_file_name = "log.json"

os.environ["http_proxy"] = read_config_value(config_file, 'Proxy', 'http_proxy')
os.environ["https_proxy"] = read_config_value(config_file, 'Proxy', 'https_proxy')
has_obsidian = False

def write_to_log_json(file_name, text):
    # 获取当前时间
    current_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    
    # 构造日志条目的JSON对象
    log_entry = {
        "timestamp": current_time,
        "message": text
    }
    
    # 将日志条目写入JSON格式的日志文件
    with open(file_name, 'a', encoding='utf-8') as file:
        json.dump(log_entry, file, ensure_ascii=False, indent=4)
        file.write('\n')  # 添加一个换行符，以便下一个条目能够从新的一行开始

def main():
    delimiter = "####"
    notice = f"\n(The user input message will be delimited with {delimiter} characters.)"

    # 获取当前脚本的绝对路径
    script_path = os.path.abspath(__file__)
    # 获取当前脚本所在文件夹的路径
    script_dir = os.path.dirname(script_path)
    # 构建json文件的绝对路径
    data_path = os.path.join(script_dir, json_file)
    full_data = load_data_from_file(data_path)

    display_options(full_data)
    print(f"\n请输入对应数字来选择所需功能:", end="")
    choice = get_user_choice(min_num=1, max_num=len(full_data))
    data = full_data[list(full_data.keys())[choice-1]]

    system_content = data.get("system_content", "")
    system_content = system_content + "\n" + notice
    user_assistant_contents = data.get("user_assistant_contents", [])

    # 总的长度为 user_content + assistant_content + system_content
    # user_content 和 assistant 数量一样
    total_len = len(user_assistant_contents) * 2 + 1
    message_list = [content2dic(role="system", content=system_content)]

    for user_content, assistant_content in user_assistant_contents:
        message_list.extend([
            content2dic(role="user", content=user_content, delimiter="####"),
            content2dic(role="assistant", content=assistant_content)
        ])

    is_multi_line = ('True' == read_config_value(config_file, 'Options', 'is_multi_line'))
    category = data['category']
    obsidian_path = r'E:/obsidian/note/English/'
    # folder_path = r'English/' + category
    folder_path = os.path.join(r'English', category)

    if has_obsidian:
        word_path = os.path.join(obsidian_path, r'word')
        story_path = os.path.join(obsidian_path, r'story')
    else:
        word_path = os.path.join(r'English', r'word')
        story_path = os.path.join(r'English', r'story')


    try:
        # 创建 vocabulary 文件夹（如果不存在）
        os.makedirs(folder_path, exist_ok=True)
        os.makedirs(obsidian_path, exist_ok=True)
    except Exception as e:
        print(f'创建文件夹时出现错误: {e}')

    if ("word" == data['category']):
        while True:
            process_word_category(word_path, message_list, delimiter, total_len, is_multi_line)
            # write_to_log_json(log_file_name, message_list)
    elif ("story" == data['category']):
        word_files = get_all_files(word_path)
        while True:
            process_story_category(story_path, word_files, message_list, delimiter, total_len, is_multi_line)
            # write_to_log_json(log_file_name, message_list)
    else:
        while True:
            process_other_category(folder_path, message_list, delimiter, total_len, is_multi_line)
            # write_to_log_json(log_file_name, message_list)

if __name__ == '__main__':
    main()

